import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author gao
 * @date 2025/8/21 15:28
 */

public class EchoClient {
    private Socket socket;

    public EchoClient(String severIP, int serverPort) throws IOException {
        socket = new Socket(severIP, serverPort);
    }

    public void start() {
        System.out.println("客户端启动！");
        Scanner in = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                // 从控制台读取用户的输入
                System.out.print("> ");
                String request = in.next();
                // 构造请求发送给服务器
                writer.println(request);
                writer.flush();
                // 读取服务器的响应
                if (!scannerNet.hasNext()) {
                    System.out.println("服务器断开了连接！");
                    break;
                }
                String response = scannerNet.next();
                // 响应显示到控制台上
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        EchoClient client = new EchoClient("127.0.0.1", 9090);
        client.start();
    }
}